// packageF/tourAround/tourSearchPage/tourSearchPage.js
const app = getApp();
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    query: {
      //筛选商品的
      page: 1,
      longitude: "",
      latitude: "",
      city: "",
      cityCode:"",
      travel_around_goods_type: 0,
      is_recommand: 0,
      category: 0,
      title: "",
      basic_info:1
    },
    isLoadMore: true,
    page: 1,
    total_page: 0,
    siteName:'',
    imageUrl:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if ((options.keyword ?? "") !== "") {
      this.setData({
        'query.title': options.keyword.trim()
      })
    }
    this.setData({
      'query.city':options.city,
      'query.cityCode':options.cityCode,
      'query.latitude':options.latitude,
      'query.longitude':options.longitude,
      'query.page':1
    })
    let arr = wx.getStorageSync("searchHistory") || [];
    let searchArr = [];
    if (arr.length > 0) {
      arr = JSON.parse(arr);
      let len = arr.length;
      if (len >= 10) {
        arr.pop();
      }
    }
    let timer = Date.parse(new Date());
    arr.unshift({ name: this.data.query.title, key: timer });
    searchArr = arr.filter((currentValue, currentIndex, selfArr) => {
      //去重
      return selfArr.findIndex(x => x.name === currentValue.name) === currentIndex;
    });
    wx.setStorageSync("searchHistory", JSON.stringify(searchArr));
    this.getGoodsList();
  },
  changeTitle(event) {
    this.setData({
      'query.page': 1,
      'query.title': event.detail.value
    })
  },
  goodsNavTo(event) {
    let id = event.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: '/packageF/tourAround/tourAroundGoodsDetails/tourAroundGoodsDetails?goodsId=' + id,
    });
  },
  confirmTap(event) {
    this.setData({
      'query.page': 1,
      'query.title': event.detail.value
    })
    this.getGoodsList();
  },
  searchClick() {
    this.getGoodsList();
  },
  getGoodsList() {
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getGoodsList");
    app._postNetWork({
      url: urlStr,
      data:this.data.query,
      success:  (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.totalPage = res.data.last_page;
          let basicInfo = res.basic_info;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          this.setData({
            goodsList: res.data.data,
            siteName:basicInfo?.home?.mailInfo?.name,
            imageUrl:basicInfo?.home?.mailInfo?.logo_url,
          })
        } else {
          this.data.query.page = this.data.query.page - 1;
          this.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //获取更多数据
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.query.page >= this.data.totalPage) {
      return;
    } else {
      this.data.query.page = this.data.query.page + 1;
      let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getGoodsList");
      app._getNetWork({
        url: urlStr,
        data: this.data.query,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              goodsList : this.data.goodsList.concat(list),
            })
          } else {
            this.data.query.page = this.data.query.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
     //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
     wx.showLoading({
      title: '刷新中...',
    })
    let query = {
       //筛选商品的
       page: 1,
       longitude: "",
       latitude: "",
       city: "",
       travel_around_goods_type: 0,
       is_recommand: 0,
       category: 0,
       title: ""
    }
    this.setData({
      query: query
    })
    this.getGoodsList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '周边游-' + this.data.siteName,
      imageUrl:this.data.imageUrl,
      path: `/packageF/tourAround/tourSearchPage/tourSearchPage?keyword=${this.data.query.title}&city=${this.data.query.city}&latitude=${this.data.query.latitude}&longitude=${this.data.query.longitude}&cityCode=${this.data.query.cityCode}`
    };
  },
  onShareTimeline() {
    return {
      title: '周边游-' + this.data.siteName,
      imageUrl:this.data.imageUrl,
      path: `/packageF/tourAround/tourSearchPage/tourSearchPage?keyword=${this.data.query.title}&city=${this.data.query.city}&latitude=${this.data.query.latitude}&longitude=${this.data.query.longitude}&cityCode=${this.data.query.cityCode}`
    };
  }
})